<template>
	<div id="orderDetails">
		<van-dialog
            v-model="isShowChatBox"
            title="留言"
            show-cancel-button
            @confirm="confirm"
            @cancel="cancel"
            >
            <div style="margin: 10px 0">
                <van-cell-group :border="false">
                    <van-field
                        v-model="charMsg"
                        rows="2"
                        autosize
                        type="textarea"
                        placeholder="请输入您的留言"
                        show-word-limit
                    />
                </van-cell-group>
            </div>
         </van-dialog>

		<van-nav-bar title="订单信息" left-text="返回" left-arrow @click-left="onClickLeft">
			<template slot="right">
				<div class="btn-box">
					<van-button size="small" square type="info" text="申请开票" @click="ApplyForinvo"
						:disabled="(details.invoice_record && details.invoice_record.status=='等待开票')"
						v-if="!(details.invoice_record && details.invoice_record.invoice_number) && details.status !== '已撤案'" />
					<van-button size="small"
						v-if="(details.invoice_record && details.invoice_record.invoice_number)"
						:disabled="(details.invoice_record && ['等待退款', '退款成功'].includes(details.invoice_record.refund))"
						square type="warning" text="申请退款"
						@click="ApplyForrefund" />
				</div>
			</template>
		</van-nav-bar>
	
		<van-collapse v-model="activeNames" :accordion="true">
			<div class="step">
				<van-steps
					:active="active"
					active-icon="circle"
					active-color="#07c160"
					>
					<van-step v-for="step in stepsText" :key="step">{{step}}</van-step>
				</van-steps>
			</div>
			<van-collapse-item name="1">
				<template slot="title">
					订单信息
				</template>
				<template slot="value">
					查看详情
				</template>
				<template slot="default">
					<viewOrderTemplate :dataResouce="dataResouce" :pageDataList="pageDataList" :isShowChat="true" @onChat="onChat($event)"></viewOrderTemplate>
				</template>
			</van-collapse-item>
			<van-collapse-item name="2">
				<template slot="title">
					流程进度
				</template>
				<template slot="value">
					查看详情
				</template>
				<template slot="default">
					<van-divider :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }">流程进度</van-divider>
					<light-timeline :items='statuss'>
						<template slot='tag' slot-scope='{ item }'>
							<h2 v-if="statussIndex[item.index]" :style="'color: '+(item.name!=''?'mediumseagreen':'#949fa8')+';'">{{statussIndex[item.index]}}</h2>
						</template>
						<template slot='content' slot-scope='{ item }'>
							<p style="margin-bottom: 0;" v-if="item.name!=''">{{item.pivot.created_at}}</p>
							<p style="margin-bottom: 0;" v-if="item.name==''">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</p>
							<h4 style="margin-top: 3px;" v-if="item.name!=''">
								<template v-if="item.id==1">{{'提交成功,本次订单您的专属顾问是'+details.process.email_work.split("@")[0].split("followup")[1]+'号'+ `联系方式：${details.process.phone}`}}</template>
								<template v-if="item.id==2">{{'订单已分配代理人'+details.agent.name + `,联系方式：${details.agent.phone}` +'。案件撰写中'}}</template>
								<template v-if="item.id==3">{{'案件撰写完毕,内审中'}}</template>
								<template v-if="item.id==4">{{'案件内审通过'}}</template>
								<template v-if="item.id==5">{{'案件内审未通过'}}</template>
								<template v-if="item.id==7">{{'案件定稿文件已上传'}}</template>
								<template v-if="item.id==8">{{'等待提交国知局'}}</template>
								<template v-if="item.id==10">{{'代理人'+details.agent_name+'已发送定稿文件'}}</template>
								<template v-if="item.id==12">{{'代理人变更为'+details.agent_name}}</template>
								<template v-if="item.id==13">{{'发明人确认定稿'}}</template>
								<template v-if="item.id==14">{{'案件已撤案'}}</template>
							</h4>
							<h4 style="margin-top: 3px;" v-if="item.name==''">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</h4>
						</template>
					</light-timeline>
				</template>
				<template slot="icon"></template>
			</van-collapse-item>
			<van-button v-if="details.status !== '已撤案'" :disabled="remingDisabled" style="width: 100%;" size="small" type="primary" @click="remind(details.id, details.remind_count, details.remind_at)">催单</van-button>
		</van-collapse>
	</div>
</template>

<script>
	import { Dialog, Toast  } from 'vant'
	import { getTimes } from '~/util/getTime'
	import viewOrderTemplate from '~/components/_viewOrder'

	export default {
		transition:'need',
		data() {
			return {
				charMsg: '',
				charName: '',
				isShowChatBox: false,
				baseUrls: global.baseurl,
				order:{},
				dataResouce: [],
				show:true,
				details: {},
				page: 1,
				active: 0,
				statuss: [],
				statussIndex: {}, //状态的id对象。key为索引
				maxId:0,
				stepsText: ['提交申请', '代理人接单', '案件撰写', '案件质控', '发明人定稿', '案件上传', '递交国知局'],
				activeNames: '1',
				invoiceArr: [],
				newInvArr: [],
				remingDisabled: false,
				oldTime: '',
				newTime: '',
				pageDataList: [
					'专利名称', '专利类型', '订单编号', '状态', '代理人', '专属顾问', '专利权人', '发明人','身份证号', '联络人', '联络人邮箱', 
					'联络人电话', '技术领域', '技术背景', '技术问题', '技术方案', '项目优势', '具体实施方式', '附图', '附件'
				]
			}
		},
		created() {
			// this.$axios.get('/api/order/'+this.$route.params.id).then(res => {
			// 	if(res.data.code == 200){
			// 		this.details = res.data.data
			// 		this.setStepStatus()
			// 	}
			// })
			this.getCurrentOrderList()
			let that = this;
			//我的订单列表
			that.$axios.get('/api/consumer/order')
			.then(res => {}).then(res => {
				//我的发票信息列表
				return that.$axios.get('/api/inv')
			})
			.then(res => {
				if (res.data.code == 200) {
					that.invoiceArr = res.data.data;
				}
			})

			that.$axios.get('/api/consumer/invoice').then(res => {
				if(res.status === 200 && res.data.code === 200) {
					that.newInvArr = res.data.data
				}
			})

		},
		methods: {
			getCurrentOrderList() {
				let id = this.$route.params.id
				this.$axios.get(`/api/order/${id}`).then(res => {
					if(res.data.code == 200){
						this.details = res.data.data
						this.dataResouce = [
							{ label: '专利名称', value: this.details.patent_name },
							{ label: '专利类型', value: this.details.type },
							{ label: '订单编号', value:  this.details.order_number },
							{ label: '状态', value: this.details.status },
							{ label: '代理人', value: this.details.agent ? this.details.agent.name : '' },
							{ label: '专属顾问', value: this.details && this.details.process ? this.details.process.email_work : ''},
							{ label: '专利权人', value: this.details.patent_user },
							{ label: '发明人', value: this.details.user_name },
							{ label: '身份证号', value: this.details.id_card },
							{ label: '联络人', value: this.details.liaisons },
							{ label: '联络人邮箱', value: this.details.liaisons_email },
							{ label: '联络人电话', value:  this.details.liaisons_tel },
							{ label: '技术领域', value: this.details.territory },
							{ label: '技术背景', value: this.details.background },
							{ label: '技术问题', value: this.details.problem },
							{ label: '技术方案', value: this.details.plan },
							{ label: '项目优势', value: this.details.advantage },
							{ label: '具体实施方式', value: this.details.path },
							{ label: '附图', value: this.details.img },
							{ label: '附件', value: this.details.file },
						]
						this.setStepStatus()
					}else{
						this.$toast('请求错误');
					}
				})
			},
			onClickLeft() {
				this.$router.go(-1);
			},
			ApplyForinvo() {
				Dialog.confirm({
					// message: '是否申请开票'
					message: `开票申请须知<br>（仅限已缴费用户使用, 未缴费用户请勿申请<br>开票为电子普票，直接发送至开票者邮箱，请确保邮箱可以正常使用<br>#有疑问请联系：严经理，13164620214`
				}).then(() => {
					this.$router.push({
						name:'user-invoice',
						params:{
							invoiceArr: this.invoiceArr,
							order_number: this.details.order_number,
							details: this.details,
							newInvArr: this.newInvArr,
						}
					})
				}).catch(() => {
					Dialog.close
				});
			},
			ApplyForrefund() {
				Dialog.confirm({
					message: '是否申请退款'
				}).then(() => {
					this.$router.push({
						name: 'user-refund',
						params: {
							id:this.details.invoice_record.id
						}
					})
				}).catch(() => {
					Dialog.close
				})
			},
			remind(id, remind_count, remind_at) {
				Dialog.confirm({
					message: '是否催单'
				}).then(() => {
					if(remind_count <= 3) {
						this.$axios(`/api/consumer/order/${id}/remind`).then(res => {
							if(res.status === 200) {
								Toast('催单成功');
								this.remingDisabled = true
							}
						})
					}else{
						Toast('已达到催单上限');
					}
				}).catch(() => {
					Dialog.close
				});
			},
			getBtnStatus(remind_at) {
				if(remind_at){
					let oldTime = (new Date(remind_at)).getTime()
					let newTime = new Date().getTime()
					if(newTime - newTime >= 3600000) {
						this.remingDisabled = false
					}else{
						this.remingDisabled = true
					}
				}else{
					this.remingDisabled = false
				}
			},
			// 1 2 3 4 13 10 8
			setStepStatus() {
				let idList = this.details.statuss.map(item => item.id)
				if(idList.includes(8)) {
					this.active = 6
					return
				}
				if(idList.includes(13)) {
					this.active = 5
					return
				}
				if(idList.includes(10)) {
					this.active = 4
					return
				}
				if(idList.includes(4)) {
					this.active = 3
					return
				}
				if(idList.includes(3)) {
					this.active = 2
					return
				}
				if(idList.includes(2)) {
					this.active = 1
					return
				}
				if(idList.includes(1)) {
					this.active = 0
					return
				}
			},
			onChat(name) {
				this.charMsg = ''
				this.charName = name
				this.isShowChatBox = true
			},
			confirm() {
				if(this.charName === '代理人') {
					if(this.charMsg) {
							this.$axios.post(`/api/consumer/${this.details.id}/message`, {
							message: this.charMsg
						}).then(res => {
							if(res.status === 200) {
								Toast(`留言成功, 已发送至${this.details.agent.email_work}邮箱`);
								this.isShowChatBox = false
							}else{
								Toast('留言失败')
								this.isShowChatBox = false
							}
						})
					}else{
						Toast('请输入您留言信息')
					}
				}else{
					if(this.charMsg) {
						this.$axios.post(`/api/consumer/${this.details.id}/process/message`, {
							message: this.charMsg
						}).then(res => {
							if(res.status === 200) {
								Toast(`留言成功, 已发送至${this.details.process.email_work}邮箱`);
								this.isShowChatBox = false
							}else{
								Toast('留言失败');
								this.isShowChatBox = false
							}
						})
					}else{
						Toast('请输入您留言信息')
					}
				}
			},
			cancel() {
				this.isShowChatBox = false
			}
		},
		updated(){
			let arr = document.getElementsByClassName('item-circle');
			for(let i = 0;i<arr.length;i++){
				//需要置灰的
				if(i >this.maxId){
					arr[i].style.border='2px solid gray';
				}
				//需要高亮
				if(i <= this.maxId){
					arr[i].style.width='20px';
					arr[i].style.height='20px';
					arr[i].style['border-radius']='25px';
					arr[i].style['margin-left']='-9px';
					arr[i].style['background']='mediumaquamarine';
				}
			}
		},
		//缓存也会走的钩子
		deactivated(){
			this.$destroy(true);//销毁组件
		},
		activated() {
			this.$axios.get('/api/order/'+this.$route.params.id)
			.then(res => {
				if(res.data.code == 200){
						this.details = res.data.data;
						// 设置催单按钮状态
						this.getBtnStatus(this.details.remind_at)
						//双边步骤条/时间轴
						let statuss = this.details.statuss;
						//大步骤。key是索引，值是需要显示的文字
						let statussIndex = {};
						//是否已有该大步骤
						let hasIndex = {
							1: false,
							2: false,
							3: false,
							4: false,
							13: false,
							7: false,
							8: false,
						}
						//防止一直倒序的bug
						if(statuss[0].id != 1){
							statuss.reverse();
						}
						for (let i = 0; i < statuss.length; i++) {
							statuss[i].index = i;
							if (statuss[i].id == 1) {
								if (!hasIndex[1]) {
									statussIndex[i] = '提交申请';
									hasIndex[1] = true;
								}
							} else if (statuss[i].id == 2) {
								if (!hasIndex[2]) {
									statussIndex[i] = '代理人接单';
									hasIndex[2] = true;
								}
							} else if (statuss[i].id == 3) {
								if (!hasIndex[3]) {
									statussIndex[i] = '案件撰写';
									hasIndex[3] = true;
								}
							} else if (statuss[i].id == 4) {
								if (!hasIndex[4]) {
									statussIndex[i] = '案件质控';
									hasIndex[4] = true;
								}
							} else if (statuss[i].id == 13) {
								if (!hasIndex[13]) {
									statussIndex[i] = '发明人定稿';
									hasIndex[13] = true;
								}
							} else if (statuss[i].id == 7) {
								if (!hasIndex[7]) {
									statussIndex[i] = '定稿文件上传';
									hasIndex[7] = true;
								}
							} else if (statuss[i].id == 8) {
								if (!hasIndex[8]) {
									statussIndex[i] = '递交国知局';
									hasIndex[8] = true;
								}
							}
						}
						this.maxId = statuss.length-1;
						//显示未到达的大步骤
						for (let i = statuss.length-1;i >= 0;i --) {
						if(statuss[i].id==1){
							statussIndex[statuss.length] = '代理人接单';
							statussIndex[statuss.length+1] = '案件撰写';
							statussIndex[statuss.length+2] = '案件质控';
							statussIndex[statuss.length+3] = '发明人定稿';
							statussIndex[statuss.length+4] = '定稿文件上传';
							statussIndex[statuss.length+5] = '递交国知局';
							statuss.push(...[{index:statuss.length,pivot:{created_at:''},name:''},
							{index:statuss.length+1,pivot:{created_at:''},name:''},
							{index:statuss.length+2,pivot:{created_at:''},name:''},
							{index:statuss.length+3,pivot:{created_at:''},name:''},
							{index:statuss.length+4,pivot:{created_at:''},name:''},
							{index:statuss.length+5,pivot:{created_at:''},name:''}])
							break;
						}else if(statuss[i].id==2){
							statussIndex[statuss.length] = '案件撰写';
							statussIndex[statuss.length+1] = '案件质控';
							statussIndex[statuss.length+2] = '发明人定稿';
							statussIndex[statuss.length+3] = '定稿文件上传';
							statussIndex[statuss.length+4] = '递交国知局';
							statuss.push(...[
							{index:statuss.length,pivot:{created_at:''},name:''},
							{index:statuss.length+1,pivot:{created_at:''},name:''},
							{index:statuss.length+2,pivot:{created_at:''},name:''},
							{index:statuss.length+3,pivot:{created_at:''},name:''},
							{index:statuss.length+4,pivot:{created_at:''},name:''}])
							break;
						}else if(statuss[i].id==3){
							statussIndex[statuss.length] = '案件质控';
							statussIndex[statuss.length+1] = '发明人定稿';
							statussIndex[statuss.length+2] = '定稿文件上传';
							statussIndex[statuss.length+3] = '递交国知局';
							statuss.push(...[
							{index:statuss.length,pivot:{created_at:''},name:''},
							{index:statuss.length+1,pivot:{created_at:''},name:''},
							{index:statuss.length+2,pivot:{created_at:''},name:''},
							{index:statuss.length+3,pivot:{created_at:''},name:''}])
							break;
						}else if(statuss[i].id==4){
							statussIndex[statuss.length] = '发明人定稿';
							statussIndex[statuss.length+1] = '定稿文件上传';
							statussIndex[statuss.length+2] = '递交国知局';
							statuss.push(...[
							{index:statuss.length,pivot:{created_at:''},name:''},
							{index:statuss.length+1,pivot:{created_at:''},name:''},
							{index:statuss.length+2,pivot:{created_at:''},name:''}])
							break;
						}else if(statuss[i].id==13){
							statussIndex[statuss.length] = '定稿文件上传';
							statussIndex[statuss.length+1] = '递交国知局';
							statuss.push(...[
							{index:statuss.length,pivot:{created_at:''},name:''},
							{index:statuss.length+1,pivot:{created_at:''},name:''}])
							break;
						}else if(statuss[i].id==7){
							statussIndex[statuss.length] = '递交国知局';
							statuss.push(...[
							{index:statuss.length,pivot:{created_at:''},name:''}])
							break;
						}
					}
						this.statuss = [];
						this.statuss.push(...statuss);
						for(let key in statussIndex){
							this.statussIndex[key] = statussIndex[key];
						}
						//this.statussIndex = statussIndex;
				}
			})
		},
		components: {
			viewOrderTemplate
		}
	}
</script>

<style lang="less">
	#orderDetails {
		position: relative;
		height: 100%;
		background: white;

		.btn-box{
			margin-right: -2px;
		}

		.step{
			height: 300px;

			.van-steps {
				padding: 10px 20px;
				height: 100%;
			}

			.van-steps__items{
				top: 80px;
			}

			.van-hairline.van-step.van-step--horizontal:nth-child(even){
				.van-step__title{
					width: 100px;
					position: relative;
					top: -30px;
				}
			}

			.van-hairline.van-step.van-step--horizontal:nth-child(odd){
				.van-step__title{
					width: 100px;
					position: relative;
					left: 10px;
					top: 80px;
				}
			}

			.van-hairline.van-step.van-step--horizontal:first-child{
				.van-step__title{
					width: 100px;
					position: relative;
					left: -15px;
					top: 80px;
				}
			}

			.van-hairline.van-step.van-step--horizontal:last-child{
				.van-step__title{
					width: 100px;
					position: relative;
					left: 15px;
					top: 80px;
				}
			}
		}

		/deep/ .van-collapse-item__content{
			padding: 0;
		}

		/deep/ .van-cell__right-icon{
			display: none;
		}

		// /deep/ .van-cell__title.van-field__label{
		// 	width: auto;
		// }

		.line-container {
			margin-left: -50px;
			margin-right: 80px;
			box-sizing: border-box;
			.gray-item-circle{
				border: 2px solid gray;
			}
			.item-tag {
				top: -18px;/*no*/
				width: 200px;//auto;
				left: -320px;
				font-size: auto;
			}

			.line-item {
				padding: 0;
			}

			&::after {
				height: calc(100%);
				//width: auto;//为了虚线，不要这个。否则ul的li连线变成双线条
				//border: 1px dashed #e4e1fe;/*no*/
			}
			.item-circle{
				border: 2px solid mediumseagreen;/*no*/
			}
		}
	}
</style>
